<template>
  <div class="list">
    <x-data-table
      v-if="getProps.pageIdList.length > 0 || getProps.productIdList.length > 0"
      ref="tableRef"
      v-model:immediate="immediate"
      v-model:checked-row-keys="checkedRowKeys"
      :params="paginationParams"
      :size="10"
      :columns="columns"
      :toolbar="false"
      :row-key="(row) => row.id"
      row-class-name="text-sm"
      @update:checked-row-keys="handleCheck"
    />

    <x-empty v-else class="empty" description="无数据" />
  </div>
</template>

<script setup lang="ts">
  import { XButton, XDataTable, XIcon, XEmpty } from '@/components'
  import { computed, h, onMounted, reactive, ref, VNode, watch } from 'vue'
  import { DataTableRowKey, NEllipsis, NPopover, NSpace, NTag, NText } from 'naive-ui'
  import { AdPageListModel } from '@/api/model/advertisingModel'
  import { PageInfo } from '@/views/advertising/page/components'
  import { useDictionary } from '@/hooks'

  const props = defineProps({
    pageIdList: {
      type: Array,
      default: () => []
    },
    productIdList: {
      type: Array,
      default: () => []
    },
    editable: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: true
    },
    selectable: {
      type: Boolean,
      default: false
    },
    checkedIds: {
      type: String,
      default: ''
    },
    params: {
      type: Object,
      default: () => ({})
    },
    moreColumns: {
      type: Boolean,
      default: false
    }
  })

  const emits = defineEmits(['delete', 'check', 'update:checkedIds'])
  const getProps = reactive(props)
  const { get: getDictionary, find: findDictionary } = useDictionary()
  const checkedRowKeys = ref<DataTableRowKey[]>([])
  const immediate = ref(true)
  const paginationParams = computed(() => {
    return {
      actions: 'advertising/adPageList',
      data: {
        pageIdList: props.pageIdList,
        productIdList: props.productIdList,
        ...props.params
      }
    }
  })

  const columnsSelection = computed(() => ({
    type: 'selection',
    multiple: getProps.multiple
  }))

  const columnRelatedProduct = reactive({
    key: 'sellingPrice',
    title: '关联商品',
    render(row: AdPageListModel): VNode {
      return h(NSpace, { vertical: true, size: 0 }, () => [
        h(NEllipsis, { lineClamp: 2 }, () => row.productTitle),
        h(NSpace, { vertical: true, size: 0, style: 'font-size: 12px;' }, () => [
          row.productShortName && h(NText, { depth: 3 }, () => `简称：${row.productShortName}`),
          row.brandName && h(NText, { depth: 3 }, () => `品牌：${row.brandName}`),
          row.productNum && h(NText, { depth: 3 }, () => `编码：${row.productNum}`),
          h(NText, { depth: 3 }, () => `ID：${row.productId}`)
        ])
      ])
    }
  })

  const columnCreatedAccount = reactive({
    key: 'creatorName',
    title: '创建账号',
    render(row: AdPageListModel): VNode {
      return h(NSpace, { vertical: true, size: 0 }, () => [
        h(NText, () => row.creatorName),
        h(NText, () => row.creatorMobile)
      ])
    }
  })

  const columnUpdatedAccount = reactive({
    key: 'editorName',
    title: '最后编辑账号',
    render(row: AdPageListModel): VNode {
      return h(NSpace, { vertical: true, size: 0 }, () => [
        h(NText, () => row.editorName),
        h(NText, () => row.editorMobile)
      ])
    }
  })

  const columnCreatedTime = reactive({
    key: 'createdAt',
    title: '创建时间'
  })

  const columnUpdatedTime = reactive({
    key: 'editedAt',
    title: '最后编辑时间',
    render(row: AdPageListModel): VNode {
      return h('div', { style: 'width: 80px' }, row.editedAt)
    }
  })

  const columnPageStatus = reactive({
    key: 'pageStatus',
    title: '页面状态',
    render(row: AdPageListModel): VNode {
      return h(NSpace, { vertical: true, size: 2, align: 'center' }, () => [
        h(NTag, { type: ['', 'success', ''][row.pageStatus], size: 'small', bordered: false }, () =>
          findDictionary(row.pageStatus, 'AD_PAGE_STATUS')
        ),
        row.rejectReason &&
          h(NSpace, { size: 2 }, () => [
            h(NTag, { type: 'error', size: 'small', bordered: false }, () => '巡检下线'),
            h(
              NPopover,
              {
                width: 300
              },
              {
                default: () => row.rejectReason,
                trigger: () => h(XIcon, { style: 'margin-left:4px', color: '#999999', name: 'icon-062' })
              }
            )
          ])
      ])
    }
  })

  const columnPageRemark = reactive({
    key: 'pageRemark',
    title: '备注',
    render(row: AdPageListModel): string {
      return row.pageRemark || '-'
    }
  })

  const columnsBase = reactive([
    {
      key: 'PageInfo',
      title: '页面信息',
      width: props.moreColumns ? 310 : '100%',
      render(row: AdPageListModel): VNode {
        return h(PageInfo, {
          detail: row,
          fullWidth: true
        })
      }
    },
    ...(props.moreColumns
      ? [
          columnRelatedProduct,
          columnCreatedAccount,
          columnUpdatedAccount,
          columnCreatedTime,
          columnUpdatedTime,
          columnPageStatus,
          columnPageRemark
        ]
      : []),
    ...(props.editable
      ? [
          {
            key: 'action',
            title: '操作',
            render(row: AdPageListModel): VNode {
              return h(XButton, { type: 'error', text: true, onClick: () => handleDelete(row) }, () => '删除')
            }
          }
        ]
      : [])
  ])

  const columns = computed(() => {
    return [...(props.selectable ? [columnsSelection.value] : []), ...columnsBase]
  })

  watch(
    () => getProps.pageIdList,
    (val) => {
      immediate.value = true
    },
    {
      deep: true
    }
  )

  watch(
    () => getProps.productIdList,
    (val) => {
      immediate.value = true
    },
    {
      deep: true
    }
  )

  watch(
    () => getProps.checkedIds,
    (val) => {
      checkedRowKeys.value = val?.split(',') || []
    },
    {
      immediate: true
    }
  )

  onMounted(() => {
    getDictionary('AD_PAGE_STATUS')
  })

  function handleDelete(row: AdPageListModel) {
    emits('delete', row.id)
  }

  function handleCheck(rowKeys: DataTableRowKey[]) {
    // checkedRowKeys.value = rowKeys
    emits('check', rowKeys)
    emits('update:checkedIds', rowKeys.join(','))
  }
</script>

<style scoped lang="scss">
  .list {
    width: 100%;
  }
</style>
